<?php

namespace app\common\service;


use app\model\FreshRechargeOrder;
use app\model\UserProgram;
use app\util\Tools;
use think\Cache;
use app\model\User as UserModel;
use think\Db;
use think\Exception;

class User{


    const USER_KEY = 'user_pin_';
    const MY_TEAM_LIST_KEY = 'my_team_list_';

    /**
     * 查询用户收货地址
     * @param int $userID
     * @param string $mobile
     * @return array
     */
    public static function getUserById($userID, $mobile){

        $key = self::USER_KEY.$userID;
        $cache = Cache::store('redis')->get($key);
        if($cache){
            $data = json_decode($cache, true);
        }else{
            $userInfo = \app\model\User::get($userID);
            $userProgramInfo = \app\model\UserProgram::get(['userID'=>$userID]);
//        $data['mobile'] = Tools::mobileDispose($userInfo['mobile']);
            $data['mobile'] =$userInfo['mobile'];
            $data['sex'] = $userInfo['sex'];
//        $data['trueName'] = $this->user['trueName'];
            $data['nickname'] = empty($userInfo['nickname']) ? Tools::mobileDispose($mobile) : $userInfo['nickname'];
            $data['photo'] = empty($userInfo['photo']) ? config('app.PHOTO') : $userInfo['photo'];
            $data['type'] = $userInfo['type'];
            $data['Qrcode'] = getQrcode(['userID' => $userInfo['userID']]);
            $data['shenfen'] = $userProgramInfo['shenfen'];
            $data['rebate'] = $userInfo['rebate'];
            Cache::store('redis')->set($key, json_encode($data), 86400);
        }
        $userProgramInfo = \app\model\UserProgram::get(['userID'=>$userID]);
        $data['freshMoney'] = $userProgramInfo['freshMoney'];
        $data['integral'] = $userProgramInfo['integral'];
        $data['freshLevel'] = $userProgramInfo['freshLevel'];
        $data['yearVip'] = $userProgramInfo['yearVip'];
        $data['yearViptext'] = $userProgramInfo['yearViptext'];
        $data['yearVipExpireTime'] = $userProgramInfo['yearVipExpireTime'];
        $data['groupMoney'] = $userProgramInfo['groupMoney'];
        $data['gambleMoney'] = $userProgramInfo['gambleMoney'];
        $data['isReplen'] = $userProgramInfo['isReplen'];
        $data['isOpen'] = config('program.isOpen');
        $freshLevel_img = config('program.freshLevel_img');
        $data['freshLevel_img'] = $freshLevel_img[$userProgramInfo['freshLevel']];
        if($userProgramInfo['yearVip'] == 0){
            $vipStatus = 0;
            $vipText = "开通年卡会员，平均可省800元/年";
        }else{
            if($userProgramInfo['yearVipExpireTime'] > time()){
                $vipStatus = 1;
                $vipText = "年卡会员至：".date("Y-m-d", $userProgramInfo['yearVipExpireTime']);
            }else{
                $vipStatus = -1;
                $vipText = "年卡会员已过期";
            }
        }
        $data['vipStatus'] = $vipStatus;
        $data['vipText'] = $vipText;
        return  $data;
    }





    /**
     * 更新商品信息
     * @param int userID
     * @return array
     * @return bool
     */
    public static function updateUser($userID, $data){

    }




    /**
     * 删除缓存
     * @param int userID 用户ID
     * @return array
     */
    public static function clearCache($userID){

    }



    /**
     * 新增用户地址
     * @param int userID 用户ID
     * @param array UserID 用户地址ID
     * @return array
     */
    public static function addUser($userID){

    }

    /**
     * 查询用户收货地址
     * @param int $userID
     * @param int $page
     * @param int $size
     * @return array
     */
    public static function getMyTeam($userID, $page, $size){

        $key = self::MY_TEAM_LIST_KEY.$userID."_".$page."_".$size;
        $cache = Cache::store('redis')->get($key);
        if($cache){
            $result = json_decode($cache, true);
        }else{
            $team_list = UserProgram::with(['user' => function($query){
                $query->field('mobile,userID,photo');
            }])->where('superID',$userID)->limit(($page - 1) * $size, $size)->order('userID desc')->select();

            $count = UserProgram::with(['user' => function($query){
                $query->field('mobile,userID');
            }])->where('superID',$userID)->count();

            $res = [];
            foreach ($team_list as $k1=>$list) {
                $res[$k1]['photo'] =  empty($list['user']['photo']) ? config('app.PHOTO') : $list['user']['photo'];
                $res[$k1]['mobile'] = Tools::mobileDispose($list['user']['mobile']);
                $res[$k1]['nickname'] = empty($list['user']['nickname']) ? Tools::mobileDispose($list['user']['mobile']) : $list['user']['nickname'];
            }
            $result = [
                'count' => $count,
                'list' => $res
            ];
            Cache::store('redis')->set($key, json_encode($result), 100);
        }
        return  $result;
    }

    /**
     * 删除用户信息缓存
     * @param int $userID 用户ID
     * @return array
     */
    public static function deleteUserCache($userID){
        $key = self::USER_KEY.$userID;
        Cache::store('redis')->rm($key);
    }

    //登录日志
    public static function log($users, $param){

        $nowtime = time();
        $save = [
            'userID'  => $users['userID'],
            'client'  => isset($param['client']) ? $param['client'] : 3,
            'appver' => isset($param['appver']) ? $param['appver'] : '',
            'telmod'  => isset($param['telmod']) ? $param['telmod'] : '',
            'telver'  => isset($param['telver']) ? $param['telver'] : '',
            'userip' => isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : '',
            'lng'  => isset($param['lng']) ? $param['lng'] : '',
            'lat'  => isset($param['lat']) ? $param['lat'] : '',
            'logtime'  => $nowtime,
            'logdate'  => date('Ymd',$nowtime),
        ];
        $table = tableName('user_login',$users['userkey']);
        $flag1 = Db::name($table)->strict(false)->insertGetId($save);

        $saves = [
            'acttime' => $nowtime,
            'actdate' => date('Ymd',$nowtime),
            'deltime' => $nowtime,
            'isline' => 1
        ];
        $flag2 = Db::name('user_info')->where('userid',$users['userid'])->strict(false)->update($saves);

        return $flag1+$flag2;
    }

    public static function getUserStatus($userID){
        $status = 3;
        $where = [
            'userID' => $userID,
            'status' => ['in', '1,2,3,4']
        ];
        $flag = Db::name('reach_order')->where($where)->count();
        if($flag == 0){
            $field = "userID, addTime";
            $user_info = Db::name('user')->field($field)->where('userID', $userID)->find();
            $time_30 = strtotime('-30days');
            if($user_info['addTime']>$time_30){
                $status = 1;    //新用户
            }
        }else{
            $where = [
                'userID' => $userID,
                'status' => ['in', '1,2,3,4'],
                'payTime' => ['>', strtotime('-30days')]
            ];
            $flag = Db::name('reach_order')->where($where)->count();
            if($flag == 0){
                $status = 2;//老用户回归
            }
        }
        return $status;
    }

    //红包雨权限：1未玩 2未领取 3已领取
    public static function getRedRainStatus($userID){

        $start_time = getConfigValue('RED_PACKET_START_TIME');
        $end_time = getConfigValue('RED_PACKET_END_TIME');
        $time = date('Y-m-d H:i:s');
        $redRainStatus = 3;
        if($time>$start_time && $time < $end_time){
            $where = [
                'addDate' => date('Ymd'),
                'userID' => $userID,
                'type' => 1
            ];
            $userPacket = Db::name('user_packet')->where($where)->find();
            if(isset($userPacket['id'])){
                if($userPacket['status'] == 1){
                    $redRainStatus = 2;
                }else{
                    $redRainStatus = 3;
                }
                $userPacket['redRainStatus'] = $redRainStatus;
                $userPacket['money'] = Tools::bcCalculate($userPacket['money'], 100, '/');
                return  $userPacket;
            }else{
                return ['redRainStatus' => 1];
            }
        }else{
            return ['redRainStatus' => $redRainStatus];
        }
    }

    //大转盘游戏权限：1未玩 2未领取 3已领取 4大转盘活动已未开放
    public static function getDialStatus($userID){
//        return ['dialStatus' => 1];
        $dial_switch = getConfigValue('DIAL_SWITCH');
        if($dial_switch == 2){
            return ['dialStatus' => 4];
        }
        $start_time = getConfigValue('DIAL_STAET_TIME');
        $end_time = getConfigValue('DIAL_END_TIME');
        $time = date('Y-m-d H:i:s');
        if($time>$start_time && $time < $end_time){
            $where = [
                'addDate' => date('Ymd'),
                'userID' => $userID,
            ];
            $userDial = Db::name('reach_dial_prize')->where($where)->find();
            if(isset($userDial['pID'])){
                $userDial['dialStatus'] = 3;
                $userDial['money'] = Tools::bcCalculate($userDial['redMoney'], 100, '/');
                return  $userDial;
            }else{
                return ['dialStatus' => 1];
            }
        }else{
            return ['dialStatus' => 4];
        }
    }

    public static function getMobileData($mobile){

        // 云市场分配的密钥Id
        $secretId = 'AKIDJ8UlxaeIb9sMP7z1p8BirNqSxebgE4d893Xa';
        // 云市场分配的密钥Key
        $secretKey = 'kt14NHgsm51bz4kA633mf269ym0o29it129yOfQq';
        $source = 'market';
        // 签名
        $datetime = gmdate('D, d M Y H:i:s T');
        $signStr = sprintf("x-date: %s\nx-source: %s", $datetime, $source);
        $sign = base64_encode(hash_hmac('sha1', $signStr, $secretKey, true));
        $auth = sprintf('hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"', $secretId, $sign);
// 请求方法
        $method = 'GET';
// 请求头
        $headers = array(
            'X-Source' => $source,
            'X-Date' => $datetime,
            'Authorization' => $auth,
        );
// 查询参数
        $queryParams = array (
            'shouji' => $mobile,
        );
// body参数（POST方法下）
        $bodyParams = array (
        );
// url参数拼接
        $url = 'https://service-hgtengxz-1257101137.ap-beijing.apigateway.myqcloud.com/release/shouji/query';
        if (count($queryParams) > 0) {
            $url .= '?' . http_build_query($queryParams);
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function ($v, $k) {
            return $k . ': ' . $v;
        }, array_values($headers), array_keys($headers)));
        if (in_array($method, array('POST', 'PUT', 'PATCH'), true)) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($bodyParams));
        }

        $data = curl_exec($ch);

        if (curl_errno($ch)) {
            curl_close($ch);
            return false;
        } else {
            curl_close($ch);
            return  json_decode($data, true);
        }
    }

    //用户升级团长
    public static  function upgradeUser($referID, $byUserID){
        $programModel = new UserProgram();
        $user_program = $programModel->where(['userID' => $referID])->find();
        if(!isset($user_program['userID'])) return true;  //推荐人不存在
        $one_num = $programModel->where(['referID' => $referID])->count();

        if($one_num>=5 && $user_program['freshLevel'] == 0){    //升级为团长
                $flag = self::userUpgradeLog($referID, $byUserID, 1); //升级为团长
                if($user_program['referID']){  //判断上上级是否有升级高级团长的条件
                    $flag = self::userGrandeTwo($user_program['referID'], $byUserID);
                }
        }
        return  true;
    }

    public static function userGrandeTwo($referID, $byUserID){
        $programModel = new UserProgram();
        $user_program = $programModel->where(['userID' => $referID])->find();
        if(!isset($user_program['userID'])) return true;  //推荐人不存在
        $one_num = $programModel->where(['referID' => $referID, 'freshLevel' => 1])->count();
        if($one_num>=5 && $user_program['freshLevel'] == 1){

            $flag = self::userUpgradeLog($referID, $byUserID, 2); //升级为高级团长
        }
        return true;
    }

    public static function userUpgradeLog($userID, $byUserID, $level){
        $model = new UserProgram();
        $user_program = $model->where(['userID' =>$userID])->find();

        if($level == 1){
            if($user_program['integralTotal']<config('program.REC_LEVEL_1')){
                return  true;
            }
        }

        if($level == 2){
            if($user_program['integralTotal']<config('program.REC_LEVEL_2')){
                return  true;
            }
        }

        if($level>$user_program['freshLevel']){
            $flag = Db::name('user_program')->where(['userID' =>$userID])->update(['freshLevel' => $level]);
            if (!$flag) throw new Exception('升级失败-1');
            $log_add = [
                'userID' => $userID,
                'byUserID' => $byUserID,
                'oldLevel' => $user_program['freshLevel'],
                'newLevel' => $level,
                'addTime' => time()
            ];
            $flag = Db::name('user_upgrade_log')->insertGetId($log_add);
            if(!$flag)throw new Exception('升级失败-2');
        }

        return true;
    }

    //只升不降
    public static function rechargeUpgrade($userID){

        $where = [
            'userID' => $userID,
            'status' => 1,
        ];
        $result = Db::name('fresh_recharge_order')->where($where)->sum('money');
        $user_pro = Db::name('user_program')->where('userID', $userID)->find();
        //金卡升级
        if($result>= 30000 && $result < 100000){
            if($user_pro['freshLevel']< 1){ //执行升级
                $flag = Db::name('user_program')->where('userID', $userID)->update(['freshLevel' => 1]);
                if(!$flag) throw new Exception('升级失败-1');
            }
        }
        //黑金卡升级
        if($result >= 100000){
            if($user_pro['freshLevel']< 2){ //执行升级
                $flag = Db::name('user_program')->where('userID', $userID)->update(['freshLevel' => 2]);
                if(!$flag) throw new Exception('升级失败-2');
            }
        }
    }


}


?>
